#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>

#define NUM 16

//char* const _env[NUM] = {(char*)"MY_105_VAL = 123456789", NULL};
// 绝对路径
const char* myfile = "/home/sz/linux/Linux/1010lesson/mycmd"; // mycmd是生成的二进制文件
int main()
{
  char* const _env[NUM] = {(char*)"MY_105_VAL=123456789", NULL};

  pid_t id = fork();
  if(id < 0)
  {
    printf("fork()");
    exit(1);
  }
  else if(id == 0)
  {
    char* const _argv[NUM] = {(char*)"ls", (char*)"-a", (char*)"-l", NULL};
    // 子进程
    printf("子进程的开始\n");
    //execl(myfile, "mycmd", "-a", NULL);
    //execlp("mycmd", "mycmd","-a", NULL); // 环境变量里面有mycmd文件的路径，所以匹配不到
    
    //execle(myfile, "mycmd", "-a", NULL, _env); //_env传给mycmd 
    //execv("/usr/bin/ls", _argv);
    
    exit(2);
    printf("子进程的结束\n");
    //exit(2);
  }
  else 
  {
    printf("父进程开始执行\n"); 
    int status = 0;
    pid_t ret = waitpid(id, &status, 0); // 阻塞式等待
    if(ret > 0)
    {
      // 等待子进程成功
      if(WIFEXITED(status)) // WEXITSTATUS判断子进程是否为正常退出，正常为真
      {
        printf("子进程执行完毕，子进程的退出码: %d\n", WEXITSTATUS(status));
      }
      else 
      {
        printf("子进程异常退出: %d\n",WIFEXITED(status));
      }
    }
  }
  return 0;
}
